package com.jvm.simulation.hotspot;

import cn.hutool.core.util.ObjectUtil;
import com.jvm.simulation.hotspot.bytecode.BasicType;
import com.jvm.simulation.hotspot.bytecode.BytecodeInterpreter;
import com.jvm.simulation.hotspot.runtime.JavaVFrame;
import com.jvm.simulation.hotspot.runtime.StackValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.InvocationTargetException;

public class JavaNativeInterface {

    private final static Logger logger = LoggerFactory.getLogger(JavaNativeInterface.class);

    public static void callStaticMethod(MethodInfo method) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        JavaThread thread = Threads.currentThread();

        if (!method.getAccessFlags().isStatic()) {
            throw new Error("只能调用静态方法");
        }

        if(thread == null){
            // 创建线程
            thread = new JavaThread();

            Threads.getThreadList().add(thread);

            Threads.setCurrentThread(thread);

            // 创建栈帧
            CodeAttribute codeAttributeInfo = method.getCodeAttributes()[0];

            JavaVFrame frame = new JavaVFrame(codeAttributeInfo.getMaxLocals(), method);

            thread.getStack().push(frame);

            logger.info("第 " + thread.getStack().size() + " 个栈帧");
        }

        // 执行任务交给字节码解释器
        BytecodeInterpreter.run(thread, method);
    }

}
